﻿using SF.API.Payment.wxpay;
using SF.Common;
using SF.Ucenter.shallWeChat;
//using SF.WeiXinComm;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace SF.Ucenter.api.wxpay
{
    public partial class payResult : System.Web.UI.Page
    {       
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //获取参数 订单号
                string otid_str = Request["otid"];
                //TM00247 购买成功通知，TM00504 消费成功通知,
                //获取 当前用户信息 订单对象
                Model.sf_user_info users = Session[SF.Common.DTKeys.SESSION_ADMIN_INFO] as Model.sf_user_info;
                Model.sf_goods_order orders = new BLL.sf_goods_order().GetModel("orderNum='" + otid_str + "' and " + SF.Common.Utils.getWhereByInfo(users.busnieseNum, users.appNum, users.templatesNum));
                //若 微信回调未成功修改 订单状态  此处进行二次修改
                if (orders.isPay<2)
                {
                    orders.isPay = 2;
                    orders.payTime = DateTime.Now;
                    bool a = new BLL.sf_goods_order().Update(orders);
                    if (a)
                    {
                        //获取商品对象
                        BLL.sf_goods_orderdetal detalBll = new BLL.sf_goods_orderdetal();
                        List<Model.sf_goods_orderdetal> orderDetal = detalBll.GetModelList("orderNum='" + orders.orderNum + "' and " + Utils.getWhereByInfo(users.busnieseNum, users.appNum, users.templatesNum));
                        BLL.sf_goods_amounts amountBll = new BLL.sf_goods_amounts();
                        //订单中第几个商品错误
                        int error = 0;
                        //遍历 商品 变更其库存
                        BLL.sf_goods_info goodBll = new BLL.sf_goods_info();
                        for (int i = 0; i < orderDetal.Count; i++)
                        {
                            Model.sf_goods_info good = goodBll.GetModel("goodsNum='" + orderDetal[i].goodsNum + "' and " + Utils.getWhereByInfo(users.busnieseNum, users.appNum, users.templatesNum));
                            Model.sf_goods_amounts amount = amountBll.GetModel(Convert.ToInt64(orderDetal[i].amountId));
                            if (amount != null && !good.goodsTypeNum.Equals("maquillage"))
                            {
                                amount.amount -= Convert.ToInt64(orderDetal[i].numbers);
                                if (!amountBll.Update(amount))
                                {
                                    error = i + 1;
                                    break;
                                }
                            }
                            else
                            {
                                good.num -= Convert.ToInt32(orderDetal[i].numbers);
                                if (!goodBll.Update(good))
                                {
                                    error = i + 1;
                                    break;
                                }
                            }
                        }
                    }
                }
                DataTable detaldt = new BLL.sf_goods_orderdetal().GetList("orderNum='" + otid_str + "' and " + SF.Common.Utils.getWhereByInfo(users.busnieseNum, users.appNum, users.templatesNum)).Tables[0];
                Model.sf_goods_info goods = new BLL.sf_goods_info().GetModel("goodsNum='" + detaldt.Rows[0]["goodsNum"] + "' and " + SF.Common.Utils.getWhereByInfo(users.busnieseNum, users.appNum, users.templatesNum));
                if (detaldt.Rows.Count > 1)
                {
                    goods.names = goods.names + "...";
                }
                Model.sf_appidmanage appModel = new BLL.sf_appidmanage().GetModel(users.appNum);
                //获取 当前用户的 上级和上上级
                DataTable dts = new BLL.sf_user_info().GetList("1!=1").Tables[0];
                DataTable dt1 = new BLL.sf_user_info().GetList("inviteKey='" + users.fatherKey + "' and " + SF.Common.Utils.getWhereByInfo(users.busnieseNum, users.appNum, users.templatesNum)).Tables[0];
                foreach (DataRow row in dt1.Rows)
                {
                    DataTable dt2 = new BLL.sf_user_info().GetList("inviteKey='" + row["fatherKey"] + "' and " + SF.Common.Utils.getWhereByInfo(users.busnieseNum, users.appNum, users.templatesNum)).Tables[0];
                    foreach (DataRow r in dt2.Rows)
                    {
                        DataRow ro = dts.NewRow();
                        ro.ItemArray = r.ItemArray;
                        dts.Rows.Add(ro);
                    }
                }
                //对 其上级 和上上级 推送消费的 模版消息
                IDictionary dict = ConfigurationManager.GetSection("weixinPay") as IDictionary;
                string inf_uri = dict["inf_uri"].ToString();
                string template_get = dict["template_get"].ToString();
                string template_send = dict["template_send"].ToString();
                api.wxpay.WebClient obj = new api.wxpay.WebClient();

                string str1 = obj.GetHtml(inf_uri + "grant_type=client_credential&appid=" + appModel.appid + "&secret=" + appModel.appsecret);
                wxaccesstoken ak = api.wxpay.JsonHelper.JsonDeserialize<wxaccesstoken>(str1);
                string str2 = obj.Post(template_get + "access_token=" + ak.access_token, "{\"template_id_short\": \"TM00247\"}");
                templateMsg tem = api.wxpay.JsonHelper.JsonDeserialize<templateMsg>(str2);
                foreach (DataRow r in dt1.Rows)
                {
                    string str3 = obj.Post(template_send + "access_token=" + ak.access_token, "{\"touser\":\"" + r["openID"] + "\",\"template_id\":\"" + tem.template_id + "\",\"url\":\"http://weixin.qq.com/download\",\"data\":{\"first\":{\"value\":\"您的一级用户【" + users.nickName + "】已成功消费！\",\"color\":\"#173177\"},\"product\":{\"value\":\"" + goods.names + "\",\"color\":\"#173177\"},\"price\":{\"value\":\"" + orders.totalMoney + "\",\"color\":\"#173177\"},\"time\":{\"value\":\"" + DateTime.Now.ToLongDateString() + "\",\"color\":\"#173177\"},\"remark\":{\"value\":\"请继续推广！\",\"color\":\"#173177\"}}}");
                }
                foreach (DataRow r in dts.Rows)
                {
                    string str3 = obj.Post(template_send + "access_token=" + ak.access_token, "{\"touser\":\"" + r["openID"] + "\",\"template_id\":\"" + tem.template_id + "\",\"url\":\"http://weixin.qq.com/download\",\"data\":{\"first\":{\"value\":\"您的二级用户【" + users.nickName + "】已成功消费！\",\"color\":\"#173177\"},\"product\":{\"value\":\"" + goods.names + "\",\"color\":\"#173177\"},\"price\":{\"value\":\"" + orders.totalMoney + "\",\"color\":\"#173177\"},\"time\":{\"value\":\"" + DateTime.Now.ToLongDateString() + "\",\"color\":\"#173177\"},\"remark\":{\"value\":\"请继续推广！\",\"color\":\"#173177\"}}}");
                }
                //对其本身也推送购买消息
                string str5 = obj.Post(template_send + "access_token=" + ak.access_token, "{\"touser\":\"" + users.openID + "\",\"template_id\":\"" + tem.template_id + "\",\"url\":\"http://weixin.qq.com/download\",\"data\":{\"first\":{\"value\":\"您已成功消费【" + orders.totalMoney + "】元，感谢您的支持！\",\"color\":\"#173177\"},\"product\":{\"value\":\"" + goods.names + "\",\"color\":\"#173177\"},\"price\":{\"value\":\"" + orders.totalMoney + "\",\"color\":\"#173177\"},\"time\":{\"value\":\"" + DateTime.Now.ToLongDateString() + "\",\"color\":\"#173177\"},\"remark\":{\"value\":\"请继续推广！\",\"color\":\"#173177\"}}}");
                //查询订单状态
                Response.Redirect("/mall/orderdetail.aspx?orderId=" + otid_str + "&type=2");
            }
        }


    }
}